package com.xumingxun.database_sync.util;

import lombok.SneakyThrows;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatabaseUtil {

    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    static Map<String,Connection> connections=new HashMap<>();
    @SneakyThrows
    public static Connection getConnection(String url, String username, String password){
        Connection conn= connections.get(url);
        if(conn==null||conn.isClosed()){
            conn=DriverManager.getConnection(url,username,password);
            connections.put(url,conn);
        }
        return connections.get(url);
    }

    @SneakyThrows
    public static void closeConnection(){
        connections.values().forEach(item-> {
            try {
                item.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @SneakyThrows
    public static Statement createStatement(String url,String username,String password){
        Connection conn=getConnection(url,username,password);
        return conn.createStatement();
    }
    @SneakyThrows
    public static void closeStatement(Statement stmt){
        stmt.close();
    }

    @SneakyThrows
    public static PreparedStatement createPreparedStatement(String url,String username,String password,String sql){
        Connection conn=getConnection(url,username,password);
        return conn.prepareStatement(sql);
    }

    @SneakyThrows
    public static int update(Statement stmt, String sql){
        return stmt.executeUpdate(sql);
    }

    @SneakyThrows
    public static List<List<Object>> queryList(Statement stmt,String sql){
        ResultSet rs= stmt.executeQuery(sql);
        List<List<Object>> result=new ArrayList<>();

        while(rs.next()){
            ResultSetMetaData meta= rs.getMetaData();
            List<Object> row=new ArrayList<>();
            for(int i=0;i<meta.getColumnCount();i++){
                row.add(rs.getObject(i+1));
            }
            result.add(row);
        }
        rs.close();
        return result;
    }

    @SneakyThrows
    public static List<Map<String,Object>> query(Statement stmt, String sql){
        ResultSet rs= stmt.executeQuery(sql);
        List<Map<String,Object>> result=new ArrayList<>();

        while(rs.next()){
            ResultSetMetaData meta= rs.getMetaData();
            Map<String,Object> row=new HashMap<>();
            for(int i=0;i<meta.getColumnCount();i++){
                row.put(meta.getColumnName(i+1),rs.getObject(i+1));
            }
            result.add(row);
        }
        rs.close();
        return result;
    }
}
